<template>
  <page-layout>
    <a-row :gutter="[10, 10]">
      <a-col :span="18">
        <context-menu :name="'dirmenu'">
          <context-menu-item @itemClickHandle="removeClick" :divider="true">{{
          t("remove")
          }}</context-menu-item>
        </context-menu>

        <context-menu :name="'boxmenu'">
          <context-menu-item @itemClickHandle="createDir" :divider="true">{{
          t("create dir")
          }}</context-menu-item>
          <context-menu-item @itemClickHandle="refreshDir" :divider="true">{{
          t("refresh")
          }}</context-menu-item>
          <context-menu-item @itemClickHandle="refreshDir" :divider="true">
            <a-upload v-model:file-list="state.fileList" :action="baseurl + '/file/upload'" :headers="headers"
              :showUploadList="false" :data="{ path: state.openedpath }" @change="Uploadchange">
              <div style="width:100%;display:block;">{{ t("upload") }} </div>
            </a-upload>
          </context-menu-item>
        </context-menu>


        <a-card>
          <a-row :gutter="[10, 10]">
            <a-col :span="24" v-if="state.showProgress">
              <a-progress :percent="state.uploadPercent" />
            </a-col>

            <a-col :span="1">
              <a-badge :color="'cyan'" :text="''" />
            </a-col>

            <a-col :span="12">
              <a-breadcrumb class="breadcrumbmenu">
                <template v-for="menu in state.menus">
                  <a-breadcrumb-item href="#" @click="directdir(menu.path)">{{
                  menu.name
                  }}</a-breadcrumb-item>
                </template>
              </a-breadcrumb>
            </a-col>
            <a-col :span="11" style="text-align: right">
              <a-space>
                <a-button @click="createDir" type="primary">{{
                t("create dir")
                }}</a-button>
                <a-button @click="refreshDir" type="primary">{{
                t("refresh")
                }}</a-button>
                <a-upload v-model:file-list="state.fileList" :action="baseurl + '/file/upload'" :headers="headers"
                  :showUploadList="false" :data="{ path: state.openedpath }" @change="Uploadchange">
                  <a-button>
                    {{ t("upload") }}
                  </a-button>
                </a-upload>
              </a-space>
            </a-col>
          </a-row>
          <a-row :gutter="[10, 10]" style="margin-top:20px" v-contextmenu="{ name: 'boxmenu'  }">
            <a-col :span="4" v-for="info in state.showfiles" style="z-index:999999"
              v-contextmenu="{ name: 'dirmenu', info: info }">
              <go2-file :name="info.name" :type="info.type" :selected="info.selected || false" @dblclick="opendir(info)"
                @click="clickfile(info)" @contextmenu="clickfile(info)"></go2-file>
            </a-col>
          </a-row>
        </a-card>
      </a-col>

      <!-- 右侧预览 -->
      <a-col :span="6" v-if="state.selectedInfo.type!=''">
        <a-card>
          <p>{{ t('name') }} : {{ state.selectedInfo.name }}</p>
          <p>{{ t('type') }} : {{ state.selectedInfo.type }}</p>
          <p>{{ t('size') }} : {{ calcSize }}</p>
          <p>{{ t('create_time') }} : {{ state.selectedInfo.create_time }}</p>
          <p v-if="isImg(state.selectedInfo.type)"><img style=" width:80%"
              :src="`${baseurl}/${state.selectedInfo.fullpath}`"></p>
          <p>
            <a-button @click="removeMethod(state.selectedInfo.fullpath)" danger block>{{t('remove')}}</a-button>
          </p>
          <p><a :href="`${baseurl}/${state.selectedInfo.fullpath}`" target="_blank">
              <a-button block>{{t('download')}}</a-button>
            </a></p>
          <p>
            <a-button type="primary" block @click="copyText(`${baseurl}/${state.selectedInfo.fullpath}`)">
              {{t('copyurl')}}</a-button>
          </p>
        </a-card>
      </a-col>
    </a-row>
  </page-layout>

  <createdir v-if="state.visibleCreatedir" :visible="state.visibleCreatedir" @close="closeCreatedir"
    :record="state.openedpath"></createdir>
</template>



<script>
import { useI18n } from "vue-i18n";
import createdir from "./modal/createdir.vue";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { list, remove, batchRemove } from "@/core/api/module/SysFile";
import { isImg, copyText } from "@/core/tools/common";
import { reactive, computed, inject, createVNode, ref, toRaw } from "vue";

const removeKey = "remove";

export default {
  components: {
    createdir,
  },
  setup() {
    const { t } = useI18n();

    const removeClick = () => {
      removeMethod(state.selectedInfo.fullpath)
    };



    const state = reactive({
      fileList: [],
      showfiles: [],
      menus: [{ name: t("root"), path: ["root"] }],
      openedpath: ["root"],
      initdata: [],
      selectedInfo: {
        type: "",
        size: 0
      },
      visibleEdit: false,
      visibleCreatedir: false,
      showProgress: false,
      uploadPercent: 0,

    });

    /// 数据来源
    const fetch = async () => {
      const response = await list();
      if (response.code == 0) {


        state.showfiles = response.data;
        state.initdata = response.data;
      }
    };

    const calcSize = computed((bytesize) => {
      //单位转换 (state.selectedInfo.size) 
      bytesize = state.selectedInfo.size || 0
      if (bytesize > 1024 * 1024) {
        bytesize = (bytesize / (1024 * 1024)).toFixed(2) + "GB";
      } else if (bytesize > 1024) {
        bytesize = (bytesize / 1024).toFixed(2) + "MB";
      } else {
        bytesize = bytesize.toFixed(2) + "KB";
      }
      return bytesize
    })

    //初始化
    fetch();
    const Uploadchange = (info) => {
      if (info.file.status == "uploading") {
        state.showProgress = true
        state.uploadPercent = info.file.percent
      }
      if (info.file.status === "done") {
        state.showProgress = false
        if (info.file.response.code == 0) {
          refreshDir();
          message.success(
            `${info.file.name} ` + t("file uploaded successfully")
          );
        } else {
          message.error(t(info.file.response.msg));
        }

      } else if (info.file.status === "error") {
        state.showProgress = false
        message.error(`${info.file.name} ` + t("file upload failed"));
      }
    };

    //刷新打开的目录
    const refreshDir = async () => {
      await fetch();
      directdir(state.openedpath);
    };

    const clickfile = (record) => {
      state.selectedInfo = record;
      state.showfiles.forEach((v) => {
        v.selected = v.fullpath == record.fullpath;
      });
    };

    const opendir = (record) => {
      if (record.type != "dir") {
        return;
      }
      state.showfiles = record.children;
      state.openedpath.push(record.name);
      state.menus.push({
        name: record.name,
        path: Object.assign([], state.openedpath),
      });
    };

    const directdir = (path) => {
      console.log("path,", path);
      let _meuns = [];
      let _path = [];
      state.showfiles = state.initdata;
      path.forEach((v) => {
        if (v != "root") {
          state.showfiles = state.showfiles.filter((x) => {
            return x.name == v;
          })[0].children;
        } else {
          state.showfiles = state.initdata;
        }
        _path.push(v);
        _meuns.push(
          Object.assign([], { name: v, path: Object.assign([], _path) })
        );
      });
      state.openedpath = Object.assign([], _path);
      state.menus = Object.assign([], _meuns);
    };

    //创建文件夹
    const createDir = () => {
      state.visibleCreatedir = true;
    };



    const closeCreatedir = function (e) {
      state.visibleCreatedir = false;
      refreshDir()
    };

    /// 删除配置
    const removeMethod = (dirname) => {
      Modal.confirm({
        title: t("confirm") + t("delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        okText: t("ok"),
        cancelText: t("cancel"),
        onOk() {
          message.loading({
            content: t("loading"),
            key: removeKey,
            duration: 0,
          });
          remove({ dirname: dirname }).then((response) => {
            if (response.code == 0) {
              message
                .success({
                  content: t("Delete succeeded!"),
                  key: removeKey,
                  duration: 1,
                })
                .then(() => {
                  refreshDir()
                });
            } else {
              message.error({
                content: response.msg,
                key: removeKey,
                duration: 1,
              });
            }
          });
        },
      });
    };


    const baseurl = window.configs.servers[localStorage.getItem("serverIndex")]['api'];
   
    const token = localStorage.getItem("USER_TOKEN");
    return {
      t,
      opendir,
      state,
      directdir,
      removeClick,
      clickfile,
      headers: { Authorization: token },
      baseurl,
      refreshDir,
      createDir,
      closeCreatedir,
      Uploadchange,
      calcSize,
      isImg,
      copyText,
      removeMethod
    };
  },
};
</script>

<style scoped>
.breadcrumbmenu {
  padding-bottom: 10px;
}
</style>